package org.jeecg.modules.wlhy.hyappmessage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.res.TaskIdDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.third.getui.push.GetuiPushService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wlhy.hyappmessage.entity.HyAppMessage;
import org.jeecg.modules.wlhy.hyappmessage.mapper.HyAppMessageMapper;
import org.jeecg.modules.wlhy.hyappmessage.service.IHyAppMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: APP消息推送
 * @Author: duanlikao
 * @Date:   2021-06-04
 * @Version: V1.0
 */
@Service
public class HyAppMessageServiceImpl extends ServiceImpl<HyAppMessageMapper, HyAppMessage> implements IHyAppMessageService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HyAppMessageServiceImpl.class);

    @Autowired
    private GetuiPushService  getuiPushService;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean pushMessage(HyAppMessage hyAppMessage){
        if(hyAppMessage == null){
            throw new JeecgBootException("推送消息不存在！");
        }
        HyAppMessage hyAppMessageDb = getById(hyAppMessage.getId());
        if(hyAppMessageDb == null){
            throw new JeecgBootException("推送消息不存在！");
        }
        GTNotification notification =  new GTNotification();

        notification.setTitle(hyAppMessageDb.getTitle());
        notification.setBody(hyAppMessageDb.getBody());
        notification.setClickType("payload");
        notification.setPayload("【河北一六八网络科技】");

        hyAppMessageDb.setSendTime(new Date());
        //推送司机
        if(hyAppMessageDb.getPushType().equals(1)){
            getuiPushService.buildApi("driver");
            ApiResult <TaskIdDTO> apiResult = getuiPushService.pushAll(notification);
            if(apiResult.isSuccess()){
                TaskIdDTO taskIdDTO = apiResult.getData();
                hyAppMessageDb.setTaskId(taskIdDTO.getTaskId());
                hyAppMessageDb.setPushStatus(1);
            }else{
                hyAppMessageDb.setPushStatus(2);
                hyAppMessageDb.setResult(JSONObject.toJSONString(apiResult));
            }
            return  updateById(hyAppMessageDb);
        }else if(hyAppMessageDb.getPushType().equals(2)) { //推送货主
            getuiPushService.buildApi("customer");
            ApiResult <TaskIdDTO> apiResult = getuiPushService.pushAll(notification);
            if(apiResult.isSuccess()){
                TaskIdDTO taskIdDTO = apiResult.getData();
                hyAppMessageDb.setTaskId(taskIdDTO.getTaskId());
                hyAppMessageDb.setPushStatus(1);
            }else{
                hyAppMessageDb.setPushStatus(2);
                hyAppMessageDb.setResult(JSONObject.toJSONString(apiResult));
            }
            return  updateById(hyAppMessageDb);
        }else { //按用户推送
            List <SysUser> sysUsers = getListSysUsersByCids(hyAppMessageDb.getCid());
            if (CollectionUtils.isEmpty(sysUsers)) {
                return false;
            }

            List <String> driverClientIds = sysUsers.stream().filter(user -> "4".equals(user.getUType()))
                    .map(SysUser::getClientId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(driverClientIds)) {
                getuiPushService.buildApi("driver");
                ApiResult <TaskIdDTO> apiResult = getuiPushService.createMsg(notification);
                if (apiResult.isSuccess()) {
                    TaskIdDTO taskIdDTO = apiResult.getData();
                    ApiResult <Map <String, Map <String, String>>> apiResults = getuiPushService
                            .pushListByCid(driverClientIds, taskIdDTO.getTaskId());

                    if(apiResults.isSuccess()){
                        hyAppMessageDb.setTaskId(taskIdDTO.getTaskId());
                        hyAppMessageDb.setPushStatus(1);
                    }else{
                        hyAppMessageDb.setPushStatus(2);
                        hyAppMessageDb.setResult(JSONObject.toJSONString(apiResults));
                    }
                    return  updateById(hyAppMessageDb);
                }
            }

            List <String> customerClientIds = sysUsers.stream().filter(user -> !"4".equals(user.getUType()))
                    .map(SysUser::getClientId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(customerClientIds)) {
                getuiPushService.buildApi("customer");
                ApiResult <TaskIdDTO> apiResult = getuiPushService.createMsg(notification);
                if (apiResult.isSuccess()) {
                    TaskIdDTO taskIdDTO = apiResult.getData();
                    ApiResult <Map <String, Map <String, String>>> apiResults = getuiPushService
                            .pushListByCid(customerClientIds, taskIdDTO.getTaskId());
                    if(apiResults.isSuccess()){
                        hyAppMessageDb.setTaskId(taskIdDTO.getTaskId());
                        hyAppMessageDb.setPushStatus(1);
                    }else{
                        hyAppMessageDb.setPushStatus(2);
                        hyAppMessageDb.setResult(JSONObject.toJSONString(apiResults));
                    }
                    return  updateById(hyAppMessageDb);
                }
            }
        }
        return false;
    }

    /**
     * 根据设备id查询用户 示例 "1，2，3"
     * @param cIds
     * @return
     */
    private List <SysUser> getListSysUsersByCids(String cIds) {
        if(StringUtils.isEmpty(cIds)){
           return new ArrayList <>();
        }
        String[] cids = cIds.split(",");
        List <String> clientIds = Arrays.asList(cids);
        QueryWrapper <SysUser> queryWrapper = new QueryWrapper <>();
        queryWrapper.in("client_id", clientIds);
        return sysUserService.list(queryWrapper);
    }

    /**
     * 停止任务 对正处于推送状态，或者未接收的消息停止下发（只支持批量推和群推任务）
     * @param hyAppMessage
     * @return
     */
    @Override
    public boolean stopMessage(HyAppMessage hyAppMessage){
        if(hyAppMessage == null){
            throw new JeecgBootException("推送消息不存在！");
        }
        HyAppMessage hyAppMessageDb = getById(hyAppMessage.getId());
        if(hyAppMessageDb == null){
            throw new JeecgBootException("推送消息不存在！");
        }

        if(StringUtils.isEmpty(hyAppMessageDb.getTaskId())){
            throw new JeecgBootException("该消息没有推送！");
        }
        boolean res = false;
        if(hyAppMessageDb.getPushType().equals(1)) {
            getuiPushService.buildApi("driver");

        }else if(hyAppMessageDb.getPushType().equals(2)) { //推送货主
            getuiPushService.buildApi("customer");
        }else { //按用户推送
            List <SysUser> sysUsers = getListSysUsersByCids(hyAppMessageDb.getCid());
            if (CollectionUtils.isEmpty(sysUsers)) {
                return false;
            }

            List <String> driverClientIds = sysUsers.stream().filter(user -> "4".equals(user.getUType()))
                    .map(SysUser::getClientId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(driverClientIds)) {
                getuiPushService.buildApi("driver");
            }
            List <String> customerClientIds = sysUsers.stream().filter(user -> !"4".equals(user.getUType()))
                    .map(SysUser::getClientId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(customerClientIds)) {
                getuiPushService.buildApi("customer");
            }

        }
        res = getuiPushService.stopPush(hyAppMessageDb.getTaskId());
        if(res){
            hyAppMessageDb.setPushStatus(3);
            updateById( hyAppMessageDb );
        }
        return  res;
    }

    /**
     * 删除定时任务 用来删除还未下发的任务，
     * 删除后定时任务不再触发(距离下发还有一分钟的任务，将无法删除，后续可以调用停止任务接口。
     * @param hyAppMessage
     * @return
     */
    @Override
    public boolean deleteMessage(HyAppMessage hyAppMessage){
        if(hyAppMessage == null){
            throw new JeecgBootException("推送消息不存在！");
        }
        HyAppMessage hyAppMessageDb = getById(hyAppMessage.getId());
        if(hyAppMessageDb == null){
            throw new JeecgBootException("推送消息不存在！");
        }
        if(StringUtils.isEmpty(hyAppMessageDb.getTaskId())){
            throw new JeecgBootException("该消息没有推送！");
        }
        Boolean res = false;
        if(hyAppMessageDb.getPushType().equals(1)) {
            getuiPushService.buildApi("driver");
        }else if(hyAppMessageDb.getPushType().equals(2)) { //推送货主
            getuiPushService.buildApi("customer");
        }else { //按用户推送
            List <SysUser> sysUsers = getListSysUsersByCids(hyAppMessageDb.getCid());
            if (CollectionUtils.isEmpty(sysUsers)) {
                return false;
            }

            List <String> driverClientIds = sysUsers.stream().filter(user -> "4".equals(user.getUType()))
                    .map(SysUser::getClientId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(driverClientIds)) {
                getuiPushService.buildApi("driver");
            }
            List <String> customerClientIds = sysUsers.stream().filter(user -> !"4".equals(user.getUType()))
                    .map(SysUser::getClientId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(customerClientIds)) {
                getuiPushService.buildApi("customer");
            }

        }
        res = getuiPushService.deleteScheduleTask(hyAppMessageDb.getTaskId());
        if(res){
            hyAppMessageDb.setPushStatus(4);
            updateById( hyAppMessageDb );
        }
        return  res;

    }



}
